package com.huangsm.book.designmodel.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 *  死锁
 * @author huang
 * @date 2019/2/21
 */
public class DieLock extends Thread{
    protected Object my;
    private static ReentrantLock lock1=new ReentrantLock();

    private static ReentrantLock lock2=new ReentrantLock();

    public DieLock(Object o) {

        this.my=o;
        if (my==lock1){
            this.setName("lock1");
        }
        if (my==lock2){
            this.setName("lock2");
        }
    }

    @Override
    public void run() {
        if (my==lock1){
            //占据了锁2
            try {
                lock2.lockInterruptibly();
                Thread.sleep(500);
                //等待锁1
                lock1.lockInterruptibly();
                System.out.println("lock1 has start");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if (lock1.isHeldByCurrentThread()){
                    lock1.unlock();
                }
                if (lock2.isHeldByCurrentThread()){
                    lock2.unlock();
                }
            }
        }
        if (my==lock2){
            //占据了锁1
            try {
                lock1.lockInterruptibly();
                Thread.sleep(500);
                //等待锁2
                lock2.lockInterruptibly();
                System.out.println("lock2 has start");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                if (lock1.isHeldByCurrentThread()){
                    lock1.unlock();
                }
                if (lock2.isHeldByCurrentThread()){
                    lock2.unlock();
                }
            }

        }
    }

    public static void main(String[] args) {
        DieLock dieLock1=new DieLock(lock1);
        DieLock dieLock2=new DieLock(lock2);
        dieLock1.start();
        dieLock2.start();
        //打破死锁状态，中断锁1
        dieLock1.interrupt();

    }

}
